/*
 * Copyright © 2016-2019 CODESTD Inc. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codestd.design.patterns.singleton;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 懒汉模式
 *
 * @author 大扑棱蛾子
 * @since 1.0.0
 */
public class LazyInstantiationConfigUtils {

    private static Logger logger = LoggerFactory.getLogger(SimpleConfigUtils.class);
    private static LazyInstantiationConfigUtils instance = null;

    private Map<String, String> props = new HashMap<>();

    /**
     * 单例的目的就是为了控制实例数量，所以构造函数一定要私有化，这样才能被其他使用者不能够随便实例化对象。
     */
    private LazyInstantiationConfigUtils() {
        this.readFromConfigFile();
        logger.info("对象实例化完成。");
    }

    /**
     * 获取配置实例
     * @return 配置实例
     */
    public static LazyInstantiationConfigUtils getInstance() {
        if (instance == null) {
            synchronized (LazyInstantiationConfigUtils.class) {
                LazyInstantiationConfigUtils inst = instance;
                if (inst == null) {
                    synchronized (LazyInstantiationConfigUtils.class) {
                        inst = new LazyInstantiationConfigUtils();
                    }
                    instance = inst;
                }
            }
        }
        return instance;
    }

    /**
     * 根据配置项的名称获取配置项的值
     * @param propName 配置项的名称
     * @return 配置项的值
     */
    public String getPropertyValue(String propName) {
        return this.props.get(propName);
    }

    private void readFromConfigFile() {
        logger.info("假装从配置文件中读取了配置");
        props.put("application.name", "DesignPattern");
        props.put("application.type", "SpringBoot");
    }
}
